package cn.javaxc.mvcwork.controller;
import cn.javaxc.mvcwork.controller.Prefs;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.prefs.Preferences;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.w3c.dom.*;
import cn.javaxc.mvcwork.util.helper.*;
import cn.javaxc.mvcwork.util.common.*;
import cn.javaxc.model.base.*;
import cn.javaxc.mvcwork.framework.database.*;
import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;

public class MVCConfig {

  private final static Logger log = Logger.getLogger(MVCConfig.class);
  public final static String fs = System.getProperty("file.separator");
  public final static String ls = System.getProperty("line.separator");
  public final static String GENERATED_MESSAGE = "### POWERED BY http://www.mydjava.com";
	protected static MVCConfig m_obj;
	public static MVCConfig getConfig(){
		return m_obj;
	}
	public static ConnectionPool getConnectionPool(){
		return m_obj.pool;
	}
	public static RequestHelper getRequestHelper(){
		return m_obj.requestHelper;
	}
	public static SQLMenu getWebmenu(){
		return m_obj.web_menu;
	}
//	public static ISQLHelper getSQLHelper(){
//		return m_obj.hqlDebug;
//	}

	public static TreeHelper getTreeHelper(){
		return m_obj.treeHelper;
	}
 	public  static String getWebContext() {
		return getConfig().getProperty("WEB.CONTEXT","");
	}
 	public  static String getWebStatic() {
		return getConfig().get("STATIC.CONTEXT",getWebContext()+MVCConstant.STATICCTX);
	}
	public SMTPHelper createSMTPHelper(){
		return new SMTPHelper();
	}

	@Autowired
	private Environment env;
  private Properties prefs = new Properties();
//  protected String prefsFile = null;
  protected RequestHelper requestHelper;
//  protected ISQLHelper hqlDebug;
  protected	SQLMenu web_menu;
  protected ConnectionPool pool;  
  protected TreeHelper treeHelper;
  public MVCConfig() {
	  requestHelper=new RequestHelper();
	  web_menu=new SQLMenu();
	  treeHelper=new TreeHelper();
  }	


//  
//  public void setPrefsFile(String tmp) {
//    this.prefsFile = tmp;
//  }
//
//
//  
//  public String getPrefsFile() {
//    return prefsFile;
//  }
//
	public void setPrefs(Properties prefs){
		this.prefs=prefs;
	}
  
  public Properties getPrefs() {
    return prefs;
  }

//  public void load() {
//	load(prefsFile);
//  }
//
//  
//  public void load(String filename) {
//    if (System.getProperty("DEBUG") != null) {
//      System.out.println("MVCConfig-> Loading prefs: " + filename);
//    }
//	File file=new File(filename);
//    try {
//	 InputStream is= new FileInputStream(file);
//     prefs.load(is);
//	 is.close();
//    } catch (Exception e) {
//      System.out.println("MVCConfig-> EXCEPTION: " + e.getMessage());
//    }
//    this.prefsFile = filename;
//	this.add("FILELIBRARY", file.getParent()+fs);
//  }

  
  public String get(String param) {
    return prefs.getProperty(param,env.getProperty(param));
  }
  public String get(String key,String _def){
	return prefs.getProperty(key,env.getProperty(key,_def));
  }
  public String getProperty(String param) {
    return get(param);
  }
  public String getProperty(String key,String _def){
	return get(key,_def);
  }
  
  public boolean has(String param) {
    return prefs.containsKey(param)||env.containsProperty(param);
  }


  
  public void clear() {
    prefs.clear();
  }

 

  
  public void add(String param, String value) {
    if (param != null) {
      if (value != null) {
        prefs.put(param, value);
      } else {
        prefs.remove(param);
      }
    }
  }



  
//  private boolean save() {
//    if (prefsFile != null) {
//      return save(prefsFile);
//    }
//    return false;
//  }
//
//
//  
//  private boolean save(String filename) {
//    try {
//      System.out.println("MVCConfig-> Saving prefs: " + filename);
//      BufferedWriter out = new BufferedWriter(new FileWriter(filename));
//      out.write(GENERATED_MESSAGE + " on " + new java.util.Date().toLocaleString() + " ###" + ls);
//      Iterator i = prefs.keySet().iterator();
//      while (i.hasNext()) {
//        String param = (String) i.next();
//        String value = (String) prefs.get(param);
//        if (param.startsWith("#")) {
//          out.write(value + ls);
//        } else {
//          out.write(param + "=" + value + ls);
//        }
//      }
//      out.close();
//      return true;
//    } catch (Exception e) {
//      return false;
//    }
//  }




  
  public final void populateContext(ServletContext context) {

	
	if (this.has("gatekeeper.driver")){
		try{
			Class.forName(this.get("gatekeeper.driver"));
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
	}
	if ("true".equals(get("layout.base","false"))){
		add("WEB.CONTEXT", "");
	}else{
		add("WEB.CONTEXT", requestHelper.getContextPath(context));
	}
	context.setAttribute("ctx", getWebContext());
	context.setAttribute("jspctx", MVCConstant.JSPCTX);
	context.setAttribute("staticctx", getWebStatic());
	context.setAttribute("staticversion", "20210322");
	SQLList elist=new SQLList();
	elist.add(elist.createElement());
	context.setAttribute("mvc_add_list",elist);
    // Verify the WEB-INF if set
    add("WebRoot", context.getRealPath("/"));
    //Define the ConnectionPool, else defaults from the ContextListener will be used
    
	
	

    // Default LAYOUT prefs
    if (!this.has("layout.template")) {
      this.add("layout.template", "template1");
    }

    if (!this.has("LAYOUT.JSP.FRAME")) {
      this.add("LAYOUT.JSP.FRAME", "easy.jsp");
    }

	context.setAttribute("mvc", this);
  }


  
  private void addParameter(ServletContext context, String param, String value) {
    addParameter(context, param, value, null);
  }


  
  private void addParameter(ServletContext context, String param, String value, String defaultValue) {
    if (value != null) {
      context.setAttribute(param, value);
    } else {
      if (defaultValue != null) {
        context.setAttribute(param, defaultValue);
      } else {
        context.removeAttribute(param);
      }
    }
  }


  
  public static String getPref(ServletContext context, String param) {
    MVCConfig prefs = (MVCConfig) context.getAttribute("mvc");
    if (prefs != null) {
      return prefs.get(param);
    } else {
      return null;
    }
  }


  
  public String toString() {
    return prefs.toString();
  }


  

  public boolean isSiteMode() {
    return "true".equals(get("WEBSERVER.ASPMODE"));
  }
  
  public String getValue(String section, String parameter, String tagName, String language) {
    return parameter;
  }


  
  public String getLabel(String section, String parameter, String language) {
    return getValue(section, parameter, "value", language);
  }


  
  public String getLabel(String parameter, String language) {
    return getLabel("system.fields.label", parameter, language);
  }



	public static int getDBType(Connection db) {
		return DatabaseUtils.getDrive(m_obj.getProperty("gatekeeper.driver"));
	}
	public  int getDBPage() {
		return DatabaseUtils.getDrive(getProperty("GATEKEEPER.PAGETYPE","none"));
	}
//	public Map getClassCfg(String cls){
//		return null;
//	}
//	public Map getClassCfg(Class cls){
//		return null;
//	}
// 	public String getClassProperty(Class cls,String property){
//		return null;
//	}
//	public String getClassProperty(String cls,String property){
//		return null;
//	}
//	public String getClassProperty(Class cls,String property,String _def){
//		return null;
//	}
//	public String getClassProperty(String cls,String property,String _def){
//		return null;
//	}
	public void addClassProperty(String cls,String property){
		add(cls,property);
	}
	public Map getClassCfg(String cls){
		return null;
	}
	public Map getClassCfg(Class cls){
		return null;
	}
	public String getClassProperty(Class cls,String property){
		if (getProperty(cls.getName()+"."+property)!=null){
			return getProperty(cls.getName()+"."+property);
		}
		return getProperty(cls.getSimpleName()+"."+property);
	}
	public String getClassProperty(String cls,String property){
		return getProperty(cls+"."+property);
	}
	public String getClassProperty(Class cls,String property,String _def){
		if (getProperty(cls.getName()+"."+property)!=null){
			return getProperty(cls.getName()+"."+property,_def);
		}
		return getProperty(cls.getSimpleName()+"."+property,_def);
	}
	public String getClassProperty(String cls,String property,String _def){
		return getProperty(cls+"."+property,_def);
	}

 	public  String getWebRoot() {
		return getProperty("WebRoot");
	}
  	public  boolean getCheckLoginSession() {
		return Boolean.valueOf(getProperty("login.checksession","false"));
//		return "true".equals(getClassProperty(SecurityHook.class,"CHECKSESSION","false"));
	}
	public  String getCheckLoginPassword() {
		return getProperty("login.weakpassword","true");
	}
	public  boolean isRollbackOnly() {
		return Boolean.valueOf(getClassProperty(MVCConfig.class,"RollbackOnly","false"));
	}
	public  String getCheckMD5Password() {
		return getProperty("login.encryptpass","true");
	}
	public  String getCheckLoginCode() {
//		return getProperty("VALIDATECODE","true");
		return getClassProperty(MVCConfig.class,"VALIDATECODE","false");
	}
	public  boolean isthickfile() {
		return false;
	}
	public String getMenuTable() {
		return getProperty("webmenu","v_menu_selmenu");
	}	
//	public void setSqlDebug(ISQLHelper hqlDebug){
//		this.hqlDebug=hqlDebug;
//	}
	public void setWebMenu(SQLMenu menu){
		this.web_menu=menu;
	}
	public void setConnectionPool(ConnectionPool pool){
		this.pool=pool;
	}


}
